package service

import (
	"context"

	"github.com/go-kratos/kratos/v2/log"

	pb "user/api/user/v1"
	"user/internal/biz"
)

type UserService struct {
	pb.UnimplementedUserServer

	uc  *biz.UserUseCase
	log *log.Helper
}

func NewUserService(uc *biz.UserUseCase, logger log.Logger) *UserService {
	return &UserService{
		uc:  uc,
		log: log.NewHelper(log.With(logger, "module", "service/user")),
	}
}

func (s *UserService) GetUser(ctx context.Context, req *pb.GetUserRequest) (*pb.GetUserReply, error) {
	user, err := s.uc.GetUser(ctx, uint(req.Id))
	if err != nil {
		return nil, err
	}

	return &pb.GetUserReply{
		Id:        int64(user.ID),
		Username:  user.Username,
		Status:    user.Status,
		CreatedAt: user.CreatedAt,
	}, nil
}

func (s *UserService) CreateUser(ctx context.Context, req *pb.CreateUserRequest) (*pb.CreateUserReply, error) {
	user, err := s.uc.CreateUser(ctx, req.Username, req.Password)
	if err != nil {
		return nil, err
	}

	return &pb.CreateUserReply{
		Id:       int64(user.ID),
		Username: user.Username,
	}, nil
}

func (s *UserService) VerifyPassword(ctx context.Context, req *pb.VerifyPasswordRequest) (*pb.VerifyPasswordReply, error) {
	success, userID, err := s.uc.VerifyPassword(ctx, req.Username, req.Password)
	if err != nil {
		return &pb.VerifyPasswordReply{
			Success: false,
			UserId:  int64(userID),
		}, err
	}

	return &pb.VerifyPasswordReply{
		Success: success,
		UserId:  int64(userID),
	}, nil
}
